package io.aicn.lowcode.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.aicn.lowcode.entity.Department;
import io.aicn.lowcode.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DepartmentService extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {
    
    @Autowired
    private DepartmentMapper departmentMapper;
    
    public List<Department> searchDepartments(String name, String code, String status) {
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Department::getName, name);
        }
        if (StringUtils.hasText(code)) {
            queryWrapper.like(Department::getCode, code);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(Department::getStatus, status);
        }
        
        return departmentMapper.selectList(queryWrapper);
    }
    
    public Department createDepartment(Department department) {
        department.setCreatedAt(LocalDateTime.now());
        department.setUpdatedAt(LocalDateTime.now());
        
        departmentMapper.insert(department);
        return department;
    }
    
    public Department updateDepartment(Long id, Department department) {
        Department existingDepartment = departmentMapper.selectById(id);
        if (existingDepartment == null) {
            return null;
        }
        
        if (department.getName() != null) {
            existingDepartment.setName(department.getName());
        }
        if (department.getCode() != null) {
            existingDepartment.setCode(department.getCode());
        }
        if (department.getDescription() != null) {
            existingDepartment.setDescription(department.getDescription());
        }
        if (department.getParentId() != null) {
            existingDepartment.setParentId(department.getParentId());
        }
        if (department.getManagerId() != null) {
            existingDepartment.setManagerId(department.getManagerId());
        }
        if (department.getLevel() != null) {
            existingDepartment.setLevel(department.getLevel());
        }
        if (department.getStatus() != null) {
            existingDepartment.setStatus(department.getStatus());
        }
        
        existingDepartment.setUpdatedAt(LocalDateTime.now());
        departmentMapper.updateById(existingDepartment);
        return existingDepartment;
    }
    
    public boolean deleteDepartment(Long id) {
        return departmentMapper.deleteById(id) > 0;
    }
}